package cn.iocoder.yudao.module.member.api.interviewInvite;

import cn.iocoder.yudao.framework.common.pojo.EmailInfo;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.member.api.curriculumVitaeSendRecord.CurriculumVitaeSendRecordApi;
import cn.iocoder.yudao.module.member.api.curriculumVitaeSendRecord.dto.CurriculumVitaeSendRecordRespDTO;
import cn.iocoder.yudao.module.member.api.curriculumVitaeSendRecord.dto.CurriculumVitaeSendRecordUpdateReqDTO;
import cn.iocoder.yudao.module.member.api.interviewInvite.dto.*;
import cn.iocoder.yudao.module.member.controller.admin.interviewInvite.vo.InterviewInviteCreateReqVO;
import cn.iocoder.yudao.module.member.controller.admin.interviewInvite.vo.InterviewInvitePageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.interviewInvite.vo.InterviewInviteReqVO;
import cn.iocoder.yudao.module.member.controller.admin.interviewInvite.vo.InterviewInviteUpdateReqVO;
import cn.iocoder.yudao.module.member.convert.interviewInvite.InterviewInviteConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.company.CompanyDO;
import cn.iocoder.yudao.module.member.dal.dataobject.interviewInvite.InterviewInviteDO;
import cn.iocoder.yudao.module.member.dal.dataobject.job.MemberJobDO;
import cn.iocoder.yudao.module.member.dal.dataobject.student.StudentDO;
import cn.iocoder.yudao.module.member.service.company.CompanyService;
import cn.iocoder.yudao.module.member.service.interviewInvite.InterviewInviteService;
import cn.iocoder.yudao.module.member.service.job.MemberJobService;
import cn.iocoder.yudao.module.member.service.student.StudentService;
import cn.iocoder.yudao.module.system.api.message.MessageApi;
import cn.iocoder.yudao.module.system.api.message.dto.MessageCreateReqDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsSendApi;
import cn.iocoder.yudao.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 投递记录 API 接口
 *
 * @author 芋道源码
 */
@Service

public class InterviewInviteApiImpl implements InterviewInviteApi {

     @Resource
     private InterviewInviteService interviewInviteService;
     @Resource
     private CurriculumVitaeSendRecordApi curriculumVitaeSendRecordApi;
     @Resource
     private MemberJobService memberJobService;
     @Resource
     private StudentService studentService;
     @Resource
     private SmsSendApi smsSendApi;
     @Resource
     private MessageApi messageApi;
     @Resource
     private CompanyService companyService;
     @Resource
     private ThreadPoolTaskExecutor threadPoolTaskExecutor;

     @Value("${spring.profiles.active}")
     private String active;
     @Override
     public Long createInterviewInvite(InterviewInviteCreateReqDTO createReqVO) {
          InterviewInviteCreateReqVO createVO=new InterviewInviteCreateReqVO();
          BeanUtils.copyProperties(createReqVO,createVO);
          return interviewInviteService.createInterviewInvite(createVO);
     }

     @Override
     public boolean createInterviewInviteList(List<InterviewInviteCreateReqDTO> createReqVO) {
          for (InterviewInviteCreateReqDTO createReqDTO:createReqVO) {
               InterviewInviteCreateReqVO createVO=new InterviewInviteCreateReqVO();
               BeanUtils.copyProperties(createReqDTO,createVO);
               MemberJobDO memberJobDO=memberJobService.getJob(createReqDTO.getJobId());
               createVO.setLowestSalary(memberJobDO.getLowestSalary());
               createVO.setHighestSalary(memberJobDO.getHighestSalary());
               createVO.setCity(memberJobDO.getCity());
               createVO.setPracticePeriod(memberJobDO.getPracticePeriod());
               createVO.setIndustry(memberJobDO.getIndustry());
               createVO.setWorkPeriod(memberJobDO.getWorkPeriod());
               createVO.setStatus("2");
               interviewInviteService.createInterviewInvite(createVO);
               CurriculumVitaeSendRecordRespDTO curriculumVitaeSendRecordRespDTO=curriculumVitaeSendRecordApi.getCurriculumVitaeSend(createReqDTO.getStudentId(),createReqDTO.getJobId(),createReqDTO.getCompanyId(),createReqDTO.getResumeId());
               CurriculumVitaeSendRecordUpdateReqDTO curriculumVitaeSendRecordUpdateReqDTO=new CurriculumVitaeSendRecordUpdateReqDTO();
               curriculumVitaeSendRecordUpdateReqDTO.setId(curriculumVitaeSendRecordRespDTO.getId());
               curriculumVitaeSendRecordUpdateReqDTO.setStatus("2");
               curriculumVitaeSendRecordApi.updateCurriculumVitaeSend(curriculumVitaeSendRecordUpdateReqDTO);
               StudentDO studentDO=studentService.getStudent(createReqDTO.getStudentId());
               if(createReqDTO.getIsSendMsg()!=null&&createReqDTO.getIsSendMsg().equals("1")){
                    this.sendMessage(studentDO);
               }
               sendStationMessage(createReqDTO.getStudentId(),createReqDTO.getJobName(),createReqDTO.getInviteDate(),
                       createReqDTO.getInviteWay(),createReqDTO.getInviteAddress(),createReqDTO.getInviteContent());
          }
          return true;
     }



     @Async
     void sendmessage(Long type, Long id,  String title, String messageText){
          MessageCreateReqDTO messageCreateReqVO=new MessageCreateReqDTO();
          messageCreateReqVO.setPhone("");
          messageCreateReqVO.setType(type);
          messageCreateReqVO.setStatus("5");
          messageCreateReqVO.setStudentId(id);
          messageCreateReqVO.setStudentName("系统管理员");
          messageCreateReqVO.setRemark(messageText);
          messageCreateReqVO.setTitle(title);
          messageApi.sendMessage(messageCreateReqVO);
     }
     /**
      * 发送面试通知短信
      * @param studentDO
      */
     private void sendMessage(StudentDO studentDO){
          SmsSendSingleToUserReqDTO smsSendSingleToUserReqDTO=new SmsSendSingleToUserReqDTO();
          smsSendSingleToUserReqDTO.setUserId(SecurityFrameworkUtils.getLoginUserId());
          smsSendSingleToUserReqDTO.setMobile(studentDO.getMobile());
          smsSendSingleToUserReqDTO.setTemplateCode("aliyun-message");
          Map<String,Object> paraMap=new HashMap<>();
          paraMap.put("name",studentDO.getNickname());
          smsSendSingleToUserReqDTO.setTemplateParams(paraMap);
          smsSendApi.sendSingleSmsToAdmin(smsSendSingleToUserReqDTO);
     }

     @Override
     public InterviewInviteRespDTO InvitedFeedback(Long id) {
          InterviewInviteDO interviewInviteDO= interviewInviteService.getInterviewInvite(id);
          return InterviewInviteConvert.INSTANCE.convert1(interviewInviteDO);
     }

     @Override
     public List<InterviewInviteRespDTO> invitationRecord(InterviewInviteReqDTO reqDTO) {
          InterviewInviteReqVO interviewInviteReqVO=new InterviewInviteReqVO();
          BeanUtils.copyProperties(reqDTO,interviewInviteReqVO);
          List<InterviewInviteDO> list =interviewInviteService.getInterviewInviteList(interviewInviteReqVO);
          return InterviewInviteConvert.INSTANCE.convertList1(list);
     }

     @Override
     public PageResult<InterviewInviteRespDTO> getInterviewInvitePage(InterviewInvitePageReqDTO reqDTO) {
          InterviewInvitePageReqVO pageReqVO=new InterviewInvitePageReqVO();
          BeanUtils.copyProperties(reqDTO,pageReqVO);
          return InterviewInviteConvert.INSTANCE.convertPage1(interviewInviteService.getInterviewInvitePage(pageReqVO));
     }

     @Override
     public Long resultIsOpenCount(InterviewInviteReqDTO reqDTO) {
          List<String> stats=new ArrayList<>();
          stats.add("5");
          stats.add("7");
          return interviewInviteService.resultCount(reqDTO.getStudentId(),stats);
     }

     @Override
     public Long resultNoOpenCount(InterviewInviteReqDTO reqDTO) {
          List<String> stats=new ArrayList<>();
          stats.add("2");
          return interviewInviteService.resultCount(reqDTO.getStudentId(),stats);
     }


     @Override
     public boolean updateInterviewInvite(InterviewInviteUpdateReqDTO updateReqDTO) {
          InterviewInviteUpdateReqVO interviewInviteUpdateReqVO=new InterviewInviteUpdateReqVO();
          BeanUtils.copyProperties(updateReqDTO,interviewInviteUpdateReqVO);
          CurriculumVitaeSendRecordUpdateReqDTO curriculumVitaeSendRecordUpdateReqDTO=new CurriculumVitaeSendRecordUpdateReqDTO();

          curriculumVitaeSendRecordUpdateReqDTO.setId(interviewInviteUpdateReqVO.getSendRecordId());
          if(interviewInviteUpdateReqVO.getStatus().equals("3")){
               curriculumVitaeSendRecordUpdateReqDTO.setStatus("3");
          }
          if(interviewInviteUpdateReqVO.getStatus().equals("2")){
               curriculumVitaeSendRecordUpdateReqDTO.setStatus("2");
          }
          if(interviewInviteUpdateReqVO.getStatus().equals("4")){
               curriculumVitaeSendRecordUpdateReqDTO.setStatus("4");
          }
          if(interviewInviteUpdateReqVO.getStatus().equals("5")){
               curriculumVitaeSendRecordUpdateReqDTO.setStatus("5");
          }
          if(interviewInviteUpdateReqVO.getStatus().equals("6")){
               curriculumVitaeSendRecordUpdateReqDTO.setStatus("6");
          }
          if(interviewInviteUpdateReqVO.getStatus().equals("7")){
               curriculumVitaeSendRecordUpdateReqDTO.setStatus("7");
          }
          if(interviewInviteUpdateReqVO.getStatus().equals("8")){
               curriculumVitaeSendRecordUpdateReqDTO.setStatus("8");
          }
          curriculumVitaeSendRecordApi.updateCurriculumVitaeSend(curriculumVitaeSendRecordUpdateReqDTO);
          interviewInviteService.updateInterviewInvite(interviewInviteUpdateReqVO);
          if(interviewInviteUpdateReqVO.getStatus().equals("2")){
               sendStationMessage(updateReqDTO.getStudentId(),updateReqDTO.getJobName(),updateReqDTO.getInviteDate(),
                       updateReqDTO.getInviteWay(),updateReqDTO.getInviteAddress(),updateReqDTO.getInviteContent());
          }
          StudentDO studentDO=null;
          if(updateReqDTO.getIsSendMsg()!=null && updateReqDTO.getIsSendMsg().equals("1")){
               studentDO=studentService.getStudent(updateReqDTO.getStudentId());
               this.sendMessage(studentDO);
          }
          if(updateReqDTO.getIsSendEmail()!=null && updateReqDTO.getIsSendEmail().equals("1")){
               if(null==studentDO || null==studentDO.getId()){
                    studentDO=studentService.getStudent(updateReqDTO.getStudentId());
               }
               if(null!=studentDO && StringUtils.isNotBlank(studentDO.getEmail())){
                    this.sendHtmlMail(studentDO.getEmail(),updateReqDTO.getJobName(),updateReqDTO.getInviteDate(),
                            updateReqDTO.getInviteWay(),updateReqDTO.getInviteAddress(),updateReqDTO.getInviteContent());
               }
          }
          return true;
     }

     @Async
     public void sendHtmlMail(String email, String jobName,Date inviteDate,String inviteWay,String inviteAddress,String inviteContent){
          EmailInfo emailInfo=new EmailInfo();
          String companyName="";
          LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
          if(null!=loginUser){
               CompanyDO company  = companyService.getCompanyById(loginUser.getCompanyId());
               if(null==company){
                    company  = companyService.getCompanyByPhone(loginUser.getUsername());
               }
               if(null!=company && StringUtils.isNotBlank(company.getCompanyName())){
                    companyName= company.getCompanyName()+"-";
               }
          }
          emailInfo.setToUser(email);
          emailInfo.setSubject("面试邀约");
          emailInfo.setEnvironment(active);
          StringBuffer str=new StringBuffer();
          str.append("<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body>");
          String message="恭喜您，您投递的 "+companyName+jobName+" 获得面试邀约<br/>";
          message+="面试时间："+DateUtils.format(inviteDate,DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)+"<br/>";
          if(StringUtils.isNotBlank(inviteWay)){
               JSONArray jsonArray=JSONObject.parseArray(inviteWay);
               String way="";
               for (int i = 0; i <jsonArray.size() ; i++) {
                    String s = jsonArray.getString(i);
                    if("0".equals(s)){
                         if(StringUtils.isBlank(way)){
                              way+="笔试";
                         }else{
                              way+=";笔试";
                         }
                    }
                    if("1".equals(s)){
                         if(StringUtils.isBlank(way)){
                              way+="面试";
                         }else{
                              way+=";面试";
                         }
                    }
                    if("2".equals(s)){
                         if(StringUtils.isBlank(way)){
                              way+="线上沟通";
                         }else{
                              way+=";线上沟通";
                         }
                    }
               }
               message+="面试方式："+way+"<br/>";
          }
          message+="详细城市："+inviteAddress +"<br/>";
          message+="其他："+inviteContent+"<br/>";
          str.append(message);
          str.append("<p style='text-align:right; padding-right: 20px;'> <img  width='200px' src='https://demo-oss.oss-cn-beijing.aliyuncs.com/jpg/9fad169ed78a492080a3800a41d97b68.jpg'/></p>");
          str.append("<p style='text-align:right; padding-right: 20px;'>电话：0755-23372612/0755-23372649</p>");
          str.append("<p style='text-align:right; padding-right: 20px;'>contact@datarer.com</p>");
          str.append("<p style='text-align:right; padding-right: 20px;'>www.datarer.com</p>");
          str.append("</body></html>");
          emailInfo.setContent(str.toString());
          threadPoolTaskExecutor.execute(()->{
               HttpUtils.doPost("http://127.0.0.1:8085/demo/task/sendMail",JSONObject.toJSONString(emailInfo));
          });
     }
//String companyName,
     private void sendStationMessage(Long studentId,String jobName,Date inviteDate,String inviteWay,String inviteAddress,String inviteContent) {
          String companyName="";
          LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
          if(null!=loginUser){
               CompanyDO company  = companyService.getCompanyById(loginUser.getCompanyId());
               if(null==company){
                    company  = companyService.getCompanyByPhone(loginUser.getUsername());
               }
               if(null!=company && StringUtils.isNotBlank(company.getCompanyName())){
                    companyName= company.getCompanyName()+"-";
               }
          }
          String message="恭喜您，您投递的 "+companyName+jobName+" 获得面试邀约<br/>";
          message+="面试时间："+DateUtils.format(inviteDate,DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)+"<br/>";
          if(StringUtils.isNotBlank(inviteWay)){
               JSONArray jsonArray=JSONObject.parseArray(inviteWay);
               String way="";
               for (int i = 0; i <jsonArray.size() ; i++) {
                    String s = jsonArray.getString(i);
                    if("0".equals(s)){
                         if(StringUtils.isBlank(way)){
                              way+="笔试";
                         }else{
                              way+=";笔试";
                         }
                    }
                    if("1".equals(s)){
                         if(StringUtils.isBlank(way)){
                              way+="面试";
                         }else{
                              way+=";面试";
                         }
                    }
                    if("2".equals(s)){
                         if(StringUtils.isBlank(way)){
                              way+="线上沟通";
                         }else{
                              way+=";线上沟通";
                         }
                    }
               }
               message+="面试方式："+way+"<br/>";
          }
//               message+="面试城市："+address.substring(0,address.lastIndexOf("市")+1)+"<br/>";
//               message+="详细城市："+address.substring(address.lastIndexOf("市")+1,address.length())+"<br/>";
          message+="详细城市："+inviteAddress +"<br/>";
          message+="其他："+inviteContent;
          sendmessage(2l,studentId,jobName+"：面试邀约",message);
     }

     @Override
     public Long createSendInterviewInvite(SendInterviewInviteCreateReqDTO createReqVO) {
          Long cvId=curriculumVitaeSendRecordApi.sendCurriculumVitaeSendRecord(createReqVO.getJobId(),createReqVO.getStudentId(),createReqVO.getResumeId(),"2","3","1");
          InterviewInviteCreateReqDTO interviewInviteCreateReqDTO=new InterviewInviteCreateReqDTO();
          BeanUtils.copyProperties(createReqVO,interviewInviteCreateReqDTO);
          interviewInviteCreateReqDTO.setStatus("2");
          interviewInviteCreateReqDTO.setSendRecordId(cvId);
          CurriculumVitaeSendRecordUpdateReqDTO curriculumVitaeSendRecordUpdateReqDTO=new CurriculumVitaeSendRecordUpdateReqDTO();
          curriculumVitaeSendRecordUpdateReqDTO.setId(cvId);
          curriculumVitaeSendRecordUpdateReqDTO.setStatus("2");
          curriculumVitaeSendRecordApi.updateCurriculumVitaeSend(curriculumVitaeSendRecordUpdateReqDTO);
          Long id=this.createInterviewInvite(interviewInviteCreateReqDTO);
          StudentDO studentDO=studentService.getStudent(createReqVO.getStudentId());
          if(createReqVO.getIsSendMsg()!=null&&createReqVO.getIsSendMsg().equals("1")){
               this.sendMessage(studentDO);
          }
          if(createReqVO.getIsSendEmail()!=null && createReqVO.getIsSendEmail().equals("1")){
               if(null!=studentDO && StringUtils.isNotBlank(studentDO.getEmail())){
                    this.sendHtmlMail(studentDO.getEmail(),createReqVO.getJobName(),createReqVO.getInviteDate(),
                            createReqVO.getInviteWay(),createReqVO.getInviteAddress(),createReqVO.getInviteContent());
               }
          }
         if("2".equals(createReqVO.getStatus())){
              sendStationMessage(createReqVO.getStudentId(),createReqVO.getJobName(),createReqVO.getInviteDate(),
                      createReqVO.getInviteWay(),createReqVO.getInviteAddress(),createReqVO.getInviteContent());
         }
          return id;
     }

     @Override
     public List<Long> createSendInterviewInviteBatch(List<SendInterviewInviteCreateReqDTO> createReqVOs) {
          List<Long> ids=new ArrayList<>();
       for (SendInterviewInviteCreateReqDTO createReqVO:createReqVOs) {
            Long cvId = curriculumVitaeSendRecordApi.sendCurriculumVitaeSendRecord(createReqVO.getJobId(), createReqVO.getStudentId(),createReqVO.getResumeId(), "2", "3", "1");
            InterviewInviteCreateReqDTO interviewInviteCreateReqDTO = new InterviewInviteCreateReqDTO();
            BeanUtils.copyProperties(createReqVO, interviewInviteCreateReqDTO);
            interviewInviteCreateReqDTO.setStatus("2");
            interviewInviteCreateReqDTO.setSendRecordId(cvId);
            Long id = this.createInterviewInvite(interviewInviteCreateReqDTO);
            CurriculumVitaeSendRecordUpdateReqDTO curriculumVitaeSendRecordUpdateReqDTO=new CurriculumVitaeSendRecordUpdateReqDTO();
            curriculumVitaeSendRecordUpdateReqDTO.setId(cvId);
            curriculumVitaeSendRecordUpdateReqDTO.setStatus("2");
            curriculumVitaeSendRecordApi.updateCurriculumVitaeSend(curriculumVitaeSendRecordUpdateReqDTO);
            StudentDO studentDO = studentService.getStudent(createReqVO.getStudentId());
            if (createReqVO.getIsSendMsg() != null && createReqVO.getIsSendMsg().equals("1")) {
                 this.sendMessage(studentDO);
            }
            if("2".equals(createReqVO.getStatus())){
                 sendStationMessage(createReqVO.getStudentId(),createReqVO.getJobName(),createReqVO.getInviteDate(),
                         createReqVO.getInviteWay(),createReqVO.getInviteAddress(),createReqVO.getInviteContent());
            }
            ids.add(id);
       }
       return ids;
     }
}
